import { HttpException, Success } from "@/core/HttpException";
import { DateUtils } from "@/module/common";
import { Context } from "egg";


module.exports = () => {
    return async function (ctx: Context, next: () => Promise<any>) {
        try {
            let start = DateUtils.getNowFullDate()
            let st = Date.now()
            await next()
            ctx.body = {
                ...ctx.body,
                startTime: start,
                wasteTime: Date.now() - st + 'ms'
            }
        } catch (error) {
            // 当前错误是否是定义的http错误
            const isHttpException = error instanceof HttpException;

            // 如果不是，抛出异常
            if (!isHttpException) {
                // console.log(ctx, error);
                ctx.logger.error(ctx, error)
                const { method, path } = ctx;
                ctx.body = {
                    msg: '未知错误',
                    errorCode: 9999,
                    requestUrl: `${method} ${path}`
                }
                ctx.status = 500
            }// 如果是已知异常
            else {
                // 根据给error设置的相应类型设置数据类型
                if (error.responseType) {
                    ctx.response.type = error.responseType;
                }
                // 如果是文件流，则直接返回文件
                if (error.isBuffer) {
                    ctx.body = error.data
                } else {
                    ctx.body = {
                        msg: error.message,
                        errorCode: error.errorCode,
                        data: error.data
                    }
                }

                ctx.status = error.code
                if (error instanceof Success || error instanceof Buffer) {
                    ctx.logger.info(ctx)
                } else {
                    ctx.logger.error(ctx, error)
                }
            }
        }
    }
}